package com.edu.controller;

import com.edu.bean.User;
import com.edu.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Resource
    public UserService userService;

    @RequestMapping("/register")
    public String register(@Valid User user, BindingResult bindingResult, Model model){
        if(bindingResult.hasErrors()){  //判断验证是否出错
            List<FieldError> fieldErrors = bindingResult.getFieldErrors(); //获取 所有的错误信息 List<FieldError>,FieldError代表一条错误性
            Map<String,String> errors = new HashMap<>();
            for (FieldError fieldError : fieldErrors) {  //遍历所有的错误信息
                errors.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            model.addAttribute("errors",errors);
            return "forward:/register.jsp";
        }
        if (userService.userRegister(user)==-1){
            model.addAttribute("msg","用户名已存在请重新取名");
            return "forward:/register.jsp";
        }
        return "forward:/index.jsp";
    }

    @RequestMapping("/userLogin")
    public ModelAndView userLogin(User user){
        int result = userService.userLogin(user);
        ModelAndView mv = new ModelAndView();
        if(result == -1){
            mv.addObject("msg","用户名不存在!");
            mv.setViewName("login.jsp");
        }else if(result == 0){
            mv.addObject("msg","密码错误!");
            mv.setViewName("login.jsp");
        }else if(result == 1){
            mv.setViewName("/listBook");
        }
        return mv;
    }
}
